import React, { useState, useEffect } from 'react';
import { Table, Input, Button, Space, message, Typography, Card, Modal, Form, DatePicker } from 'antd';
import { SearchOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { useSelector, useDispatch } from 'react-redux'
import { addList } from './store/index'
import axios from 'axios';
import styles from './Dashboard.module.less';
import { useNavigate } from 'react-router-dom';
import type { Dayjs } from 'dayjs';
const { Title } = Typography;

// 定义商品数据接口
interface ProductItem {
  _id: string;
  name: string;
  bfs: string;
  dzs: number;
  time: string;
}
const ProductList: React.FC = () => {
  // 状态管理
  const [products, setProducts] = useState<ProductItem[]>([]);
  const [filteredProducts, setFilteredProducts] = useState<ProductItem[]>([]);
  const [searchText, setSearchText] = useState('');
  const [loading, setLoading] = useState(true);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  // 新增编辑相关状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<ProductItem | null>(null);
  const [editForm] = Form.useForm();

  const nav = useNavigate();
  const dispatch = useDispatch()
  // 假设 store 的类型为 RootState，需要根据实际情况定义该类型
  interface RootState {
    list: any;
  }
  const list1 = useSelector((store: RootState) => store.list);
  const get = async () => {
    let res = await axios.get("http://localhost:3000/get")
   
    setProducts(res.data.sj)
    setFilteredProducts(res.data.sj)
  }

  const dj = (record: ProductItem) => {
    dispatch(addList(record))
    console.log(list1);
    nav("/home2")
  }
  const sc = async (record: ProductItem) => {
    await axios.get("http://localhost:3000/sc?id=" + record._id)
    message.success('删除成功');
    get()
  }
  // 初始化数据
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      // 模拟API请求延迟
      setTimeout(() => {
        get()
        setPagination(prev => ({ ...prev, total: filteredProducts.length }));
        setLoading(false);
      }, 800);
    };

    fetchData();
  }, []);

  // 搜索功能
  useEffect(() => {
    const filtered = filteredProducts.filter(product =>
      // Add null checks for name and bfs
      (product.name || '').toLowerCase().includes(searchText.toLowerCase()) ||
      (product.bfs || '').toLowerCase().includes(searchText.toLowerCase()) ||
      product.dzs.toString().includes(searchText)
    );

    setFilteredProducts(filtered);
    setPagination(prev => ({ ...prev, current: 1, total: filtered.length }));
  }, [searchText, products]);

  // 分页处理
  const handleTableChange = (pagination: any) => {
    setPagination(pagination);
  };


  // 编辑功能实现
  const handleEdit = (record: any) => {
    console.log(record);

    setCurrentRecord(record);
    // 填充表单数据

    setIsModalVisible(true);
  };

  const handleEditSubmit = async () => {
    try {
      if (!currentRecord) return;
      // 验证并获取所有表单字段值
      const values = await editForm.validateFields();
      
      // 格式化提交数据
      const updateData = {
        ...values,
        // 日期字段格式化
        time: values.time?.format('YYYY-MM-DD'),
        // 数字字段转换
        dzs: values.dzs,
        bfs: values.bfs,
        _id: currentRecord._id
      };
  
      // 调用后端接口提交数据
      await axios.post(`http://localhost:3000/gx`, updateData);
      message.success('修改成功！');
      setIsModalVisible(false);
      get(); // 重新获取数据刷新列表
    } catch (error) {
      console.error('修改失败:', error);
      message.error('修改失败，请重试');
    }
  };


  // 表格列定义 - 修改编辑按钮事件
  const columns = [
    { title: 'ID', dataIndex: '_id', key: '_id', width: 100 },
    { title: '名称', dataIndex: 'name', key: 'name', sorter: (a: ProductItem, b: ProductItem) => a.name.localeCompare(b.name) },
    {
      title: '播放数', dataIndex: 'bfs', key: 'bfs',
    },
    { title: '点赞数', dataIndex: 'dzs', key: 'dzs', },
    { title: '历史时间', dataIndex: 'time', key: 'time' },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: ProductItem) => (
        <Space size="small">
          <Button type="text" icon={<EditOutlined />} onClick={() => handleEdit(record)}>编辑</Button>
          <Button type="text" danger icon={<DeleteOutlined />} onClick={() => sc(record)}>删除</Button>
          <Button type="text" icon={<EditOutlined />} onClick={() => dj(record)}>查看图表</Button>
        </Space>
      )
    },
  ];

  return (
    <div className={styles.container}>
      <Card className={styles.card}>
        <div className={styles.header}>
          <Title level={3} className={styles.title}>历史记录</Title>

        </div>

        <div className={styles.searchBar}>
          <Input
            placeholder="搜索商品名称、ID或分类"
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={e => setSearchText(e.target.value)}
            style={{ width: 500 }}
            allowClear
          />
          <Space size="middle">
            <Button type="primary" onClick={() => nav("/add")}>添加商品</Button>

          </Space>
        </div>

        <Table
          columns={columns as any[]}
          dataSource={filteredProducts}
          rowKey="id"
          pagination={{ ...pagination, showSizeChanger: true, showTotal: total => `共 ${total} 条记录` }}
          onChange={handleTableChange}

          size="middle"
          bordered
          scroll={{ x: 'max-content' }}
        />

        {/* 编辑模态框 */}
        <Modal
          title="修改商品"
          visible={isModalVisible}
          onCancel={() => setIsModalVisible(false)}
          footer={[
            <Button key="cancel" onClick={() => setIsModalVisible(false)}>
              取消
            </Button>,
            <Button key="submit" type="primary" onClick={handleEditSubmit}>
              确定
            </Button>,
          ]}
        >
          <Form
            form={editForm}
            layout="vertical"
            name="edit_form"
            initialValues={{ name: currentRecord?.name || '', dzs: currentRecord?.dzs || 0, bfs: currentRecord?.bfs || 0, time: null }}
          >
            <Form.Item<ProductItem>
              name="name"
              label="名称"
              rules={[{ required: true, message: '请输入名称' }]}
            >
              <Input placeholder="请输入名称" />
            </Form.Item>

            <Form.Item<ProductItem>
              name="dzs"
              label="点赞数"
              rules={[
                { required: true, message: '请输入点赞数' },
               
              ]}
            >
              <Input type="number" placeholder="请输入点赞数" />
            </Form.Item>

            <Form.Item<ProductItem>
              name="bfs"
              label="播放数"
              rules={[
                { required: true, message: '请输入播放数' },
               
              ]}
            >
              <Input type="number" placeholder="请输入播放数" />
            </Form.Item>

            <Form.Item<ProductItem>
              name="time"
              label="历史时间"
         
            >
              <DatePicker placeholder="请选择时间" style={{ width: '100%' }} />
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  );
};
export default ProductList;



